﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECRMS.Biz.Dom;
using ECRMS.Data;
using System.Data.Linq;
using ECRMS.Common;

namespace ECRMS.Biz
{
	public class CtIndexLogic
	{
        //得到某个公司目前在用的指标组
        public CtServiceResult<CtIndexHistroy> GetIndexByCorpId(Guid corpId)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    return new CtServiceResult<CtIndexHistroy>
                    {
                        Data = (from a in dataContext.GetTable<CSRCorpIndexHistory>()
                                where a.CorpRefId == corpId
                                select new CtIndexHistroy { 
                                  CorpIndexHistoryId=a.CorpIndexHistoryRefId,
                                  CorpRefId=a.CorpRefId,
                                  CreateDate=a.CreateDate,
                                  IsRatable=a.IsRatable,
                                  Items=GetItemByHistroyId(a.CorpIndexHistoryRefId,dataContext),
                                  Score=a.Score
                                }).ToList()[0],
                        Status = 1

                    };
                }
                catch (Exception)
                {

                    return new CtServiceResult<CtIndexHistroy>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }

            }
        }

        private List<CtIndexHistroyItem> GetItemByHistroyId(Guid guid, CSRManagerSystemDBDataContext dataContext)
        {
            return (from a in dataContext.GetTable<CSRCorpIndexHistoryItem>() 
                   join b in dataContext.GetTable<CSRIndex>() on a.IndexRefId equals b.IndexRefId
                   join c in dataContext.GetTable<CSRInputType>() on b.InputTypeId equals c.InputTypeId
                   join d in dataContext.GetTable<CSRUser>() on a.UserRefId equals d.UserRefId into temp1
                   from dLeft in temp1.DefaultIfEmpty()
                   select new CtIndexHistroyItem { 
                        AssignedUserName=dLeft.Name,
                        AssignedUserRefId=a.UserRefId,
                        CorpIndexHistoryItemRefId=a.CorpIndexHistoryItemRefId,
                        Description=b.Description,
                        IndexRefId=b.IndexRefId,
                        InputTypeId=b.InputTypeId,
                        InputTypeName=c.Name,
                        Keyword=b.Keyword,
                        MaxValue=c.MaxValue,
                        MinValue=c.MinValue,
                        Name=b.Name,
                        ParentIndexRefId=b.ParentIndexRefId,
                        Percentage=b.Percentage,
                        Score=a.Score,
                        SeqId=b.SeqId
                   }).ToList();
        }

        //得到某个组某个员工的的所有指标列表,这里的指标返回格式有所不一样,而且只返回最低级别的指标
        public CtServiceResult<List<CtIndexProcess>> GetIndexByCorpIdAndUserId(Guid corpId, Guid userId, int userTypeId)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    List<CtIndexHistroyItem> employeeIndexs = new List<CtIndexHistroyItem>();
                    //如果是管理员 那么列出所有的指标集合，不管他在分配的时候只分配到一点
                    if (userTypeId == (int)AuthorityEnum.CorporationClientAdmin)
                    {
                        employeeIndexs = GetIndexByCorpId(corpId).Data.Items.Where(p => p.InputTypeId != null).ToList();
                    }
                    else
                    {
                        //当前被指定给此员工的indexs
                        employeeIndexs = GetIndexByCorpId(corpId).Data.Items.Where(p => p.AssignedUserRefId == userId && p.InputTypeId != null).ToList();
                    }


                    //最终此员工会得到的指标==结果集
                    List<CtIndexHistroyItem> employeeAllIndexs = GetIndexByCorpId(corpId).Data.Items.Where(p => p.AssignedUserRefId == userId && p.InputTypeId != null).ToList();
                    List<CtIndexHistroyItem> allIndexs = GetIndexByCorpId(corpId).Data.Items;

                    foreach (CtIndexHistroyItem index in employeeIndexs)
                    {
                        if (index.ParentIndexRefId != null && index.ParentIndexRefId != Guid.Empty)
                        {
                            RecursionIndex(index, employeeAllIndexs, allIndexs);
                        }
                    }
                    List<CtIndexProcess> processes = ChangeToIndexProcess(employeeIndexs, employeeAllIndexs);
                    return new CtServiceResult<List<CtIndexProcess>>
                    {
                        Data = processes,
                        Status = 1

                    };
                }
                catch (Exception)
                {

                    return new CtServiceResult<List<CtIndexProcess>>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }

            }
        }

        //添加关联的父节点
        private void RecursionIndex(CtIndexHistroyItem index, List<CtIndexHistroyItem> employeeAllIndexs, List<CtIndexHistroyItem> allIndexs)
        {
            //首先判断结果集中是否有父节点 如有有的话 就不添加了
            if (employeeAllIndexs.FirstOrDefault(p => p.IndexRefId == index.ParentIndexRefId) == null)
            {
                //添加父节点到结果集
                CtIndexHistroyItem ix = allIndexs.FirstOrDefault(p => p.IndexRefId == index.ParentIndexRefId);
                employeeAllIndexs.Add(ix);
                if (ix.ParentIndexRefId != null && ix.ParentIndexRefId != Guid.Empty)
                {
                    RecursionIndex(ix, employeeAllIndexs, allIndexs);
                }

            }
        }

        //这边的lowIndex是最低级别的指标,indexs是全部指标
        //把指标编程可以测评用的指标
        public List<CtIndexProcess> ChangeToIndexProcess(List<CtIndexHistroyItem> lowIndexs, List<CtIndexHistroyItem> indexs)
        {
            List<CtIndexProcess> processes = new List<CtIndexProcess>();
            foreach (CtIndexHistroyItem item in lowIndexs)
            {
                int level = 1;//起始值设置成为第一级目录
                if (item.ParentIndexRefId != null && item.ParentIndexRefId != Guid.Empty)
                {
                    level = GetProcessLevel(level, item.ParentIndexRefId, indexs);
                }

                processes.Add(new CtIndexProcess
                {
                    CorpHistroyItemRefId = item.CorpIndexHistoryItemRefId,
                    Description = item.Description,
                    IndexParentRefID = item.ParentIndexRefId,
                    IndexRefId = item.IndexRefId,
                    InputTypeId = (int)item.InputTypeId,
                    InputTypeName = item.InputTypeName,
                    Level = level,
                    MaxValue = item.MaxValue,
                    MinValue = item.MinValue
                });

            }
            foreach (CtIndexProcess process in processes)
            {
                for (int i = 1; i <= process.Level; i++)
                {
                    CtIndexHistroyItem index = lowIndexs.FirstOrDefault(p => p.IndexRefId == process.IndexRefId);
                    switch (i)
                    {
                        case 1:
                            process.Name1 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 2:
                            process.Name2 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 3:
                            process.Name3 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 4:
                            process.Name4 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 5:
                            process.Name5 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 6:
                            process.Name6 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 7:
                            process.Name7 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 8:
                            process.Name8 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        case 9:
                            process.Name9 = GetProcessName(process.Level - i, index, indexs);
                            break;
                        default:
                            break;
                    }
                }
            }

            return processes;
        }

        //
        private string GetProcessName(int num, CtIndexHistroyItem index, List<CtIndexHistroyItem> indexs)
        {
            for (int i = 1; i <= num; i++)
            {
                index = indexs.FirstOrDefault(p => p.IndexRefId == index.ParentIndexRefId);
            }
            return index.Name + "(" + index.Percentage + ")";
        }

        private int GetProcessLevel(int count, Guid indexId, List<CtIndexHistroyItem> indexs)
        {
            count++;
            if (indexs.FirstOrDefault(p => p.IndexRefId == indexId).ParentIndexRefId != Guid.Empty)
            {
                count = GetProcessLevel(count, indexs.FirstOrDefault(p => p.IndexRefId == indexId).ParentIndexRefId, indexs);
            }
            return count;
        }

        //更新某个指标组的数据,用于指标分配
        public CtServiceResult<CtIndexHistroy> UpdateIndexs(CtIndexHistroy index)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    foreach (CtIndexHistroyItem item in index.Items)
                    {
                        CSRCorpIndexHistoryItem ins = dataContext.GetTable<CSRCorpIndexHistoryItem>().FirstOrDefault(p => p.CorpIndexHistoryItemRefId == item.CorpIndexHistoryItemRefId);
                        if (ins != null && item.AssignedUserRefId != Guid.Empty)
                        {
                            ins.UserRefId = item.AssignedUserRefId;
                        }
                    }
                    dataContext.SubmitChanges();
                    return GetIndexByCorpId(index.CorpRefId);
                }
                catch (Exception)
                {

                    return new CtServiceResult<CtIndexHistroy>
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }

            }
        }

        public CtServiceResult UpdateIndexProcess(List<CtIndexProcess> indexes)
        {
            using (var dataContext = CSRManagerSystemDBDataContext.NewInstance())
            {
                try
                {
                    foreach (CtIndexProcess item in indexes)
                    {
                        CSRCorpIndexHistoryItem corpIndex = dataContext.GetTable<CSRCorpIndexHistoryItem>().FirstOrDefault(p => p.CorpIndexHistoryItemRefId == item.CorpHistroyItemRefId);
                        corpIndex.Score = item.Score;
                    }
                    dataContext.SubmitChanges();
                    return new CtServiceResult
                    {
                        Status = 1
                    };
                }
                catch (Exception)
                {

                    return new CtServiceResult
                    {
                        Message = "try_catch_exception",
                        Status = 0
                    };
                }
            }
        }


        //****************************指标打分方法**********************
        //首先还是先保存到corpindex，然后从corpindex表中拿出数据进行比较

        //public CtServiceResult<decimal> EvaluateIndexGroup(List<CtIndexProcess> processes, Guid corpIndexGroupRefId)
        //{
        //    using (var dataContext = ECRMSDataContext.NewInstance())
        //    {
        //        try
        //        {
        //            //最后得分
        //            decimal indexGroupScore = 0;
        //            //公司指标组
        //            ECCorpIndexGroup indexGroup = dataContext.GetTable<ECCorpIndexGroup>().FirstOrDefault(p => p.CorpIndexGroupRefId == corpIndexGroupRefId);
        //            //所有的数据指标
        //            List<ECCorpIndex> CorpIndexs = dataContext.GetTable<ECCorpIndex>().Where(p => p.CorpIndexGroupRefId == corpIndexGroupRefId).ToList();
        //            //所有的指标
        //            List<CtIndexHistroy> indexs = GetIndexByCorpId(corpIndexGroupRefId).Data;

        //            //先保存最后一级指标
        //            foreach (CtIndexProcess process in processes)
        //            {
        //                CorpIndexs.FirstOrDefault(p => p.CorpIndexRefId == process.CorpIndexRefId).Score = process.Score;
        //            }
        //            //保存最后一级指标完毕后，在此测试一下是不是全部的指标都已经填写完毕
        //            //一般情况下是不会出现这种情况的，因为客户端已经做过限制了
        //            int num1 = indexs.Where(p => p.InputTypeId != null).Count();//当前总共有几个指标需要填写
        //            int num2 = CorpIndexs.Where(p => p.Score != null).Count();//目前已经有多少指标已经填写了
        //            if (num1 > num2)
        //            {
        //                return new CtServiceResult<decimal>
        //                {
        //                    Status = 0,
        //                    Message = "index_not_score"
        //                };
        //            }

        //            //如果以上没有问题，开始测评从最后一级指标开始运算

        //            //先定义一个递推的结果集
        //            List<CtIndexHistroy> IndexsCahe = new List<CtIndexHistroy>();

        //            //再定义一个当前需要循环遍历的集合
        //            List<CtIndexHistroy> IndexsLoop = new List<CtIndexHistroy>();

        //            //先把最后一级的指标放入IndexsLoop
        //            IndexsCahe.AddRange(indexs.Where(p => p.InputTypeId != null).ToList());

        //            //当IndexsCahe中的所有的指标都变成
        //            while (IndexsCahe.Where(p => p.ParentID != null).Count() == 0)
        //            {
        //                LoopIndexResult(indexs, IndexsCahe, CorpIndexs);
        //            }

        //            foreach (CtIndexHistroy item in IndexsCahe)
        //            {
        //                indexGroupScore = indexGroupScore + Convert.ToDecimal(item.Score) * item.Percentage;
        //            }

        //            indexGroup.StatusId = 1;
        //            indexGroup.Score = indexGroupScore * 100;

        //            dataContext.SubmitChanges();
        //            return new CtServiceResult<decimal>
        //            {
        //                Status = 1,
        //                Data = indexGroupScore * 100
        //            };

        //        }
        //        catch (Exception)
        //        {
        //            return new CtServiceResult<decimal>
        //            {
        //                Message = "try_catch_exception",
        //                Status = 0
        //            };
        //        }
        //    }


        //}

        //private void LoopIndexResult(List<CtIndexHistroy> indexs, List<CtIndexHistroy> IndexsCahe, List<ECCorpIndex> CorpIndexs)
        //{
        //    List<CtIndexHistroy> IndexsLoop = new List<CtIndexHistroy>();
        //    IndexsLoop.AddRange(IndexsCahe);
        //    IndexsCahe.Clear();
        //    foreach (CtIndexHistroy item in IndexsLoop)
        //    {
        //        if (item.ParentID == null)//是一级指标了
        //        {
        //            IndexsCahe.Add(item);
        //        }
        //        else
        //        {

        //            //找到父节点
        //            CtIndexHistroy parentIndex = indexs.FirstOrDefault(p => p.ID == item.ParentID);

        //            //如果已经添加到IndexsCahe中去了，那么就不需要再计算了
        //            if (IndexsCahe.FirstOrDefault(p => p.ID == parentIndex.ID) == null)
        //            {
        //                decimal score = 0;
        //                List<CtIndexHistroy> list = indexs.Where(p => p.ParentID == parentIndex.ID).ToList();
        //                foreach (CtIndexHistroy item1 in list)
        //                {
        //                    //如果是1到9分或者0-9分的话 是先要除一下的
        //                    if (item1.InputTypeId == (int)IndexTypeEnum.OneToNine || item1.InputTypeId == (int)IndexTypeEnum.ZeroToNine)
        //                    {
        //                        score = score + (Convert.ToDecimal(item1.Score) * item.Percentage) / 9;
        //                    }
        //                    else
        //                    {
        //                        score = score + Convert.ToDecimal(item1.Score) * item.Percentage;
        //                    }

        //                }

        //                parentIndex.Score = score;
        //                //同时需要更新数据库的cropindex表
        //                CorpIndexs.FirstOrDefault(p => p.CorpIndexRefId == parentIndex.CorpIndexRefId).Score = score;

        //                //把父节点放到下一轮需要遍历的结果集中去
        //                IndexsCahe.Add(parentIndex);
        //            }
        //        }
        //    }
        //}
    }
}
